const express = require('express')
const { send } = require('process')
const app = express()
const port = 8000

// 定义路由规则
app.get('/', (request, response) => {    
    response.send('Hello World!')
})

app.get('/getRequest', (request, response) => {
    // 设置响应头 允许跨域，允许任意来源
    response.setHeader('Access-Control-Allow-Origin', '*')   
    response.send('Hello get!')
})

// post方式请求
app.post('/postRequest', (request, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*')
    response.send('Hello post!')
})

// 允许任意请求方式
app.all('/set', (request, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*')
    // 设置响应头 设置允许任意请求头名
    response.setHeader('Access-Control-Allow-Headers', '*')
    
    response.send('Hello set!')
})

// JSON响应
app.all('/jsonServer', (request, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*')
    response.setHeader('Access-Control-Allow-Headers', '*')
    
    const data = {name: 'beauty'}
    // send中必须是字符串类型，所以用json.stringify转换为一个字符串
    response.send(JSON.stringify(data))
})

// 延时响应
app.get('/delay', (request, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*')
    
    // 3秒后返回响应体
    setTimeout(()=>{
        response.send('Hello World!')
    },3000)
})

// 针对缓存
app.all('/catch', (request, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*')
    
    // 更改响应体来测试缓存
    // response.send('Hello catch! - 0')
    response.send('Hello catch! - 9')
})

// 针对fetch方式
app.all('/fetchServer', (request, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*')
    response.setHeader('Access-Control-Allow-Headers', '*')
    
    const data = {name: 'fetch'}
    response.send(JSON.stringify(data))
})

// 针对jsonp解决跨域
app.all('/jsonpServer', (request, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*')
    response.setHeader('Access-Control-Allow-Headers', '*')
    
    // 接收回调函数
    const callback = request.query.callback
    const data = {name: 'hello jsonp'}
    // 执行这个回调函数，将响应体以参数形式带过去
    response.send(`${callback}(${JSON.stringify(data)})`)
})

// 针对cors
app.all('/cors', (request, response) => {
    // response.setHeader('Access-Control-Allow-Origin', '*')
    response.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:5500')
    
    response.send('Hello cors!')
})

app.use((request, response, next) => {
    console.log('有人请求8000服务器了！')
    console.log('请求的资源是', request.path)
    console.log('请求的来源是', request.get('Host'))
    next()
})
app.get('/students', (request, response) => {
    const data = [
        {id: 001,name: '张三',grade: '大一'},
        {id: 002,name: '李四',grade: '大一'},
        {id: 003,name: '王五',grade: '大一'},       
    ]
    response.send(JSON.stringify(data))
})



app.listen(port, () => {
    console.log(`app 服务已经启动，http://localhost:${port} 监听中....`)
})